package hars

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"release/catch"
	"release/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	title := c.PostForm("title")
	data := models.Release{
		Name:  name,
		Title: title,
	}
	if name == "" || title == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
			"data": nil,
		})
		return
	}
	models.DB.Create(&data)
	var release []models.Release
	redis_key := "redis_key" + strconv.Itoa(int(data.ID))
	models.DB.Where("id = ?", data.ID).First(&release)
	jsondata, _ := json.Marshal(&release)
	catch.Rdb.Set(catch.Ctx, redis_key, jsondata, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id = ?", id).Delete(&models.Release{})
	redis_del := "redis_key" + id
	catch.Rdb.Del(catch.Ctx, redis_del)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
		"data": nil,
	})
	return

}
func List(c *gin.Context) {
	var release []models.Release

	redis_list := "redis_list"
	catchcount, _ := catch.Rdb.Get(catch.Ctx, redis_list).Result()
	if catchcount == "" {
		models.DB.Find(&release)
		jsondata, _ := json.Marshal(&release)
		catch.Rdb.Set(catch.Ctx, redis_list, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(catchcount), &release)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": release,
	})
	return
}
